import { defineStore } from 'pinia'
import { type Ref, ref } from 'vue'
import type { User } from '@/modules/admin/manager/entity'
import type { CurrentUser } from '@/modules/security/entity'

export const useCurrentUserStore = defineStore('currentUser', () => {
  const currentUser = ref<CurrentUser>({ user: {} as User, roles: [],menus:[],operate:[],routes:[], Authorization: "" }) as Ref<CurrentUser>
  // 初始化时从 localStorage 读取 token
  const storedToken = localStorage.getItem('Authorization')
  if (storedToken) {
    if (currentUser.value) {
      currentUser.value.Authorization = storedToken;
    }
  }
  function setUser(info: CurrentUser) {
    // 给 user 赋值
    if (currentUser.value) {
      currentUser.value.user = info.user;
      currentUser.value.roles = info.roles;
      currentUser.value.menus = info.menus;
      currentUser.value.operate = info.operate;
    }
  }

  function setToken(newToken: string) {
    if (currentUser.value) {
      currentUser.value.Authorization = newToken;
    }
    localStorage.setItem('Authorization', newToken) // 将 token 保存到 localStorage
  }

  function clearUser() {
    currentUser.value = { user: {} as User, roles: [],menus:[],operate:[],routes:[], Authorization: "" } as CurrentUser
    localStorage.removeItem('Authorization') // 清除 localStorage 中的 token
  }

  function isLoggedIn(){
    return currentUser.value && currentUser.value.Authorization
  }

  return { currentUser, setUser, setToken, clearUser, isLoggedIn }
})